'use strict';

import AdminShopModel from '../../models/shopping/shop'
import AddressComponent from '../../prototype/addressComponent'

/**
 * Crypto++ 库是一个用c++ 编写的密码类库，是一个自由软件。
 * crypto-js
 * */
import crypto from 'crypto'
import formidable from 'formidable'

class Admin extends AddressComponent {
	constructor() {
		super()
		this.login = this.login.bind(this)
		this.encryption = this.encryption.bind(this)
	}
	async login(req, res, next) {
		const form = new formidable.IncomingForm();
		form.parse(req, async (err, fields, files) => {
			if (err) {
				// 发送HTTP响应
				res.send({
					status: 0,
					type: 'FORM_DATA_ERROR',
					message: '表单信息错误'
				})
				return
			}
			const { user_name, password, status = 1 } = fields;
			try {
				if (!user_name) {
					throw new Error('用户名参数错误')
				} else if (!password) {
					throw new Error('密码参数错误')
				}
			} catch (err) {
				console.log(err.message, err);
				res.send({
					status: 0,
					type: 'GET_ERROR_PARAM',
					message: err.message,
				})
				return
			}
			const newpassword = this.encryption(password);
			try {
				const admin = await AdminShopModel.findOne({ name: user_name })
				// console.log(admin.id)
				if (!admin) {
					res.send({
						status: 0,
						message: '该用户不存在',
					})
				} else if (newpassword.toString() != admin.password.toString()) {
					// console.log('管理员登录密码错误');
					res.send({
						status: 0,
						type: 'ERROR_PASSWORD',
						message: '该用户已存在，密码输入错误',
					})
				} else {
					res.send({
						status: 1,
						success: '登录成功',
						id: admin.id
					})
				}
			} catch (err) {
				console.log('登录失败', err);
				res.send({
					status: 0,
					type: 'LOGIN_ADMIN_FAILED',
					message: '登录失败',
				})
			}
		})
	}
	encryption(password) {
		const newpassword = this.Md5(this.Md5(password).substr(2, 7) + this.Md5(password));
		return newpassword
	}
	Md5(password) {
		const md5 = crypto.createHash('md5');
		return md5.update(password).digest('base64');
	}
}

export default new Admin()